<template>
  <div>
    <!-- 表单 -->
    <el-form ref="deptForm" :model="deptForm" :rules="deptRules" label-width="100px">
      <!-- 表单项 -->
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" />
      </el-form-item>
      <!-- code -->
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" />
      </el-form-item>
      <!-- 下拉选项框 -->
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="deptForm.manager" placeholder="请选择部门负责人">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <!-- 文本域 -->
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="deptForm.introduce" type="textarea" />
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
        <el-button size="mini" @click="$emit('cancel',false)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getEmployeeSimple, addDepartments, getDeptDetails, editDepartment } from '@/api/department'
export default {
  name: 'DialogForm',
  props: {
    parentId: {
      type: String,
      required: true
    },

    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 自定义校验code
    const checkCode = (rules, value, callback) => {
      let codeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        // 当处于编辑的时候 需要排除当前编辑的这一项的code
        codeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      codeList.includes(value) ? callback(new Error(`部门编码${value}已经存在`)) : callback()
    }

    // 自定义校验 同级部门名称不能重复
    const checkName = (rules, value, callback) => {
      // 当前点击的这一项的id即为要添加的子级的pid
      let nameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)
      if (this.isEdit) {
        // 编辑状态
        // 找到当前编辑的这一项
        const editItem = this.originList.find(item => item.id === this.parentId)
        // 找到当前编辑的pid
        const pid = editItem.pid
        // pid相同的就是同级 且排除当前这一项的name
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.parentId).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error(`部门名称${value}已经存在`)) : callback()
    }
    return {
      deptForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      employees: [],
      deptRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getEmployeeSimple()
    this.getDeptDetails()
  },
  methods: {

    // 根据父级id 获取部门详情 回填数据
    async getDeptDetails() {
      // 如果是编辑状态
      if (this.isEdit) {
        const res = await getDeptDetails(this.parentId)
        // console.log(res)
        this.deptForm = res.data
      }
    },

    // 获取简单员工列表
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.employees = res.data
    },

    // 点击确定
    onSubmit() {
      // 兜底验证
      this.$refs.deptForm.validate(async valid => {
        if (!valid) return
        // 判断是否是编辑
        if (!this.isEdit) {
        // 添加子部门
          const data = { ...this.deptForm, pid: this.parentId }
          // console.log(data)
          const res = await addDepartments(data)
          // 失败
          if (!res.success) return this.$message.error(res.message)
          // console.log(res)
          // 成功后关闭弹出框 更新视图 提示
          this.$emit('close')
          this.$message.success(res.message)
        } else {
        // 编辑部门
          const res = await editDepartment(this.deptForm)
          // console.log(res)
          // 失败
          if (!res.success) return this.$message.error(res.message)
          // 成功后关闭弹出框 更新视图 提示
          this.$emit('close')
          this.$message.success(res.message)
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.el-select {
  width: 100%;
}
.el-form {
  padding: 0 60px 0 30px;
}
</style>
